package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNGetUserResponse;
import com.github.postsanf.yinian.utils.BigDecimalUtil;
import com.github.postsanf.yinian.utils.CashierInputFilter;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.google.gson.Gson;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.util.LinkedHashMap;

public class MyWalletgetCashDialogActivity extends Activity implements View.OnClickListener {
    private RelativeLayout rl_mywallet;
    private RelativeLayout dialog_mywallet;
    private RelativeLayout rl_tixian1;
    private RelativeLayout rl_tixian2;
    private EditText getcash_num;
    private EditText et_tixian_zhanghao;
    private ImageView mywallet_getcash_sure;
    private TextView tv_mymoney;
    private InputMethodManager imm;
    private BaseApplication application;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_dialog_mywallet_getcash);
        application = (BaseApplication) getApplication();
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        initView();
        getUserWallet();
    }

    private void initView() {
        findViewById(R.id.mywallet_leftback).setOnClickListener(this);
        findViewById(R.id.mywallet_close).setOnClickListener(this);
        findViewById(R.id.tv_pay_history).setOnClickListener(this);
        dialog_mywallet = (RelativeLayout) findViewById(R.id.dialog_mywallet);
        rl_mywallet = (RelativeLayout) findViewById(R.id.rl_mywallet);
        rl_tixian1 = (RelativeLayout) findViewById(R.id.rl_tixian1);
        rl_tixian2 = (RelativeLayout) findViewById(R.id.rl_tixian2);
        tv_mymoney = (TextView) findViewById(R.id.tv_mymoney);
        getcash_num = (EditText) findViewById(R.id.getcash_num);
        et_tixian_zhanghao = (EditText) findViewById(R.id.et_tixian_zhanghao);
        getcash_num.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getcash_num.setSelection(getcash_num.getText().length());
            }
        });
        InputFilter[] inputFilters = {new CashierInputFilter()};
        getcash_num.setFilters(inputFilters);
        mywallet_getcash_sure = (ImageView) findViewById(R.id.mywallet_getcash_sure);
        mywallet_getcash_sure.setOnClickListener(this);
        rl_tixian1.setOnClickListener(this);
        Animation translateAnimationf = new TranslateAnimation(0, 0, -UIHelper.dip2px(MyWalletgetCashDialogActivity.this, 220), 0);
        translateAnimationf.setDuration(500);
        rl_mywallet.startAnimation(translateAnimationf);
        getcash_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    mywallet_getcash_sure.setImageResource(R.drawable.mywallet_getcash_sure_press);
                } else {
                    mywallet_getcash_sure.setImageResource(R.drawable.mywallet_getcash_sure);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }


    private void getUserWallet() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowUserHead))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNGetUserResponse resUser = new Gson().fromJson(s, YNGetUserResponse.class);
                        if (resUser != null && ReqUtils.isSuccess(resUser.getCode()) && resUser.getData().size() > 0) {
                            String uBalance = resUser.getData().get(0).getuBalance();
                            if (!StringUtils.isEmpty(uBalance)) {
                                tv_mymoney.setText(uBalance);
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(this)).executeAsync(req);
    }

    @Override
    public void onBackPressed() {

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mywallet_close:
                sendBroadcast(new Intent(ACTIONs.actionCloseactivity));
                dialog_mywallet.setClickable(false);
                Animation translateAnimationf = new TranslateAnimation(0, 0, 0, UIHelper.dip2px(MyWalletgetCashDialogActivity.this, 600));
                translateAnimationf.setDuration(600);
                rl_mywallet.startAnimation(translateAnimationf);
                translateAnimationf.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        rl_mywallet.setVisibility(View.GONE);
                        finish();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
                break;
            case R.id.mywallet_leftback:
                dialog_mywallet.setClickable(false);
                Animation translateAnimationf2 = new TranslateAnimation(0, 0, 0, UIHelper.dip2px(MyWalletgetCashDialogActivity.this, 600));
                translateAnimationf2.setDuration(600);
                rl_mywallet.startAnimation(translateAnimationf2);
                translateAnimationf2.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        rl_mywallet.setVisibility(View.GONE);
                        finish();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
                break;
            case R.id.rl_tixian1:
                rl_tixian2.setVisibility(View.VISIBLE);
                rl_tixian1.setVisibility(View.GONE);
                getcash_num.setFocusable(true);
                getcash_num.setFocusableInTouchMode(true);
                getcash_num.requestFocus();
                getcash_num.setSelection(getcash_num.getText().length());
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                break;
            case R.id.mywallet_getcash_sure:
                String zhanghao = et_tixian_zhanghao.getText().toString();
                String cashNum = getcash_num.getText().toString();
                String yuer = tv_mymoney.getText().toString();
                if (StringUtils.isEmpty(zhanghao))
                    return;
                if (StringUtils.isEmpty(cashNum))
                    return;
                if (BigDecimalUtil.multotal(cashNum, "100") > BigDecimalUtil.multotal(yuer, "100")) {
                    Toast.makeText(MyWalletgetCashDialogActivity.this, "提现金额不能大于余额！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (BigDecimalUtil.multotal(cashNum, "100") < BigDecimalUtil.multotal("0.1", "100")) {
                    Toast.makeText(MyWalletgetCashDialogActivity.this, "提现金额不能小于0.1元！", Toast.LENGTH_SHORT).show();
                    return;
                }
                ToUserCash(cashNum, zhanghao);
                break;
            case R.id.tv_pay_history:
                startActivity(new Intent(this, TransactionDetailsActivity.class));
                break;
        }
    }


    private void ToUserCash(String cashNum, String zhanghao) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put("money", cashNum);
        mParam.put("account", zhanghao);
        Log.i("xjs", "ToUserCash===>" + mParam.toString());
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/user/Withdraw")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "cashhhhhh===>" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s.toString());
                            if (jsonObject.optString("msg").equals("success") && jsonObject.optInt("code") == 0) {
                                sendBroadcast(new Intent("updateMyWallet"));
                                Toast.makeText(MyWalletgetCashDialogActivity.this, "提现成功", Toast.LENGTH_SHORT).show();
                                finish();
                            } else {
                                Toast.makeText(MyWalletgetCashDialogActivity.this, "提现失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                        Toast.makeText(MyWalletgetCashDialogActivity.this, "体现失败", Toast.LENGTH_SHORT).show();
                    }
                });
        LiteHttp.newApacheHttpClient(new
                HttpConfig(this)).
                executeAsync(req);
    }


    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

}
